package com.onesports.intelligent.k12.polarlight.service.order;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onesports.intelligent.k12.polarlight.annotation.DistributedLock;
import com.onesports.intelligent.k12.polarlight.common.errors.exceptions.BusinessException;
import com.onesports.intelligent.k12.polarlight.constant.CodeConstants;
import com.onesports.intelligent.k12.polarlight.constant.LockConstants;
import com.onesports.intelligent.k12.polarlight.domain.dto.market.OrdersSettlementQueryDTO;
import com.onesports.intelligent.k12.polarlight.domain.dto.market.SettlementOrderSelectDTO;
import com.onesports.intelligent.k12.polarlight.domain.entity.market.Orders;
import com.onesports.intelligent.k12.polarlight.domain.entity.market.OrdersSettlement;
import com.onesports.intelligent.k12.polarlight.domain.entity.market.OrdersSettlementRel;
import com.onesports.intelligent.k12.polarlight.domain.vo.market.OrdersSettlementVO;
import com.onesports.intelligent.k12.polarlight.domain.vo.market.SettlementOrderSelectVO;
import com.onesports.intelligent.k12.polarlight.domain.vo.market.TotalDataVO;
import com.onesports.intelligent.k12.polarlight.mapper.market.OrdersMapper;
import com.onesports.intelligent.k12.polarlight.mapper.market.OrdersSettlementMapper;
import com.onesports.intelligent.k12.polarlight.util.CalculateUtil;
import com.onesports.intelligent.k12.polarlight.util.CodeUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrdersSettlementService extends ServiceImpl<OrdersSettlementMapper, OrdersSettlement> {

    private final OrdersSettlementRelService ordersSettlementRelService;

    private final OrderService orderService;

    private final CodeUtils codeUtils;

    public TotalDataVO<SettlementOrderSelectVO> querySettlementOrderPage(SettlementOrderSelectDTO dto) {
        checkParams(dto);
        IPage<SettlementOrderSelectVO> page = baseMapper.querySettlementOrderPage(dto.getPager(),dto);
        SettlementOrderSelectVO totalData = baseMapper.querySettlementOrderSum(dto);
        TotalDataVO<SettlementOrderSelectVO> totalDataVO = new TotalDataVO<>();
        totalDataVO.setTotalData(totalData);
        totalDataVO.setPage(page);
        return totalDataVO;
    }

    public TotalDataVO<OrdersSettlementVO> selectPage(OrdersSettlementQueryDTO dto) {
        IPage<OrdersSettlementVO> page = baseMapper.page(dto.getPager(),dto);
        OrdersSettlementVO totalData = baseMapper.settlementSum(dto);
        TotalDataVO<OrdersSettlementVO> totalDataVO = new TotalDataVO<>();
        totalDataVO.setTotalData(totalData);
        totalDataVO.setPage(page);
        return totalDataVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @DistributedLock(value = LockConstants.LOCK_SETTLEMENT_ORDER)
    public void settlementOrder(SettlementOrderSelectDTO dto) {
        checkParams(dto);
        //要结算的订单集合
        List<SettlementOrderSelectVO> orders = baseMapper.querySettlementOrderPage(dto);
        if(CollectionUtils.isEmpty(orders)){
            throw new BusinessException("未查询到订单数据");
        }
        long settlementCount = orders.stream().filter(SettlementOrderSelectVO::getSettlementStatus).count();
        if(settlementCount>0){
            throw new BusinessException("存在已结算订单，请重新查询");
        }
        //合计数据
        SettlementOrderSelectVO totalData = CalculateUtil.getSumValue(orders, SettlementOrderSelectVO.class);
        OrdersSettlement ordersSettlement = new OrdersSettlement();
        ordersSettlement.setSettlementNo(codeUtils.autoSerialNumber(CodeConstants.JS,3));
        ordersSettlement.setOrganizationId(dto.getOrganizationId());
        ordersSettlement.setStartTime(dto.getOrderStartTime());
        ordersSettlement.setEndTime(dto.getOrderEndTime());
        ordersSettlement.setSettlementTime(new Date());
        ordersSettlement.setOrderNum(orders.size());
        ordersSettlement.setActuallyAmountTotal(totalData.getActuallyAmount());
        ordersSettlement.setPlatformSubLedger(totalData.getPlatformSubLedger());
        ordersSettlement.setOrganizationSubLedger(totalData.getOrganizationSubLedger());
        ordersSettlement.setCampusSubLedger(totalData.getCampusSubLedger());
        ordersSettlement.setCoachSubLedger(totalData.getCoachSubLedger());
        ordersSettlement.setHeadSubLedger(totalData.getHeadSubLedger());
        save(ordersSettlement);

        List<OrdersSettlementRel> relList = orders.stream().map(item->{
            OrdersSettlementRel rel = new OrdersSettlementRel();
            rel.setOrderSettlementId(ordersSettlement.getId());
            rel.setOrdersId(item.getId());
            return rel;
        }).collect(Collectors.toList());


        List<String> orderIds = orders.stream().map(SettlementOrderSelectVO::getId).collect(Collectors.toList());
        //修改订单结算状态
        orderService.update(new UpdateWrapper<Orders>().lambda().set(Orders::getSettlemented,true).in(Orders::getId,orderIds));
        //添加订单结算明细
        ordersSettlementRelService.saveBatch(relList);

    }


    public void checkParams(SettlementOrderSelectDTO dto){
        if(!StringUtils.isNotBlank(dto.getOrganizationId())||null==dto.getOrderStartTime()||null==dto.getOrderEndTime()){
            throw new BusinessException("请选中运营团队跟完整的订单时间范围");
        }
    }
}
